package com.colt.contentcenter.service.place;

import com.alibaba.fastjson.JSONArray;
import com.colt.contentcenter.dao.city.CityMapper;

import com.colt.contentcenter.domain.entity.city.City;
import com.colt.contentcenter.util.RedisService;
import com.colt.contentcenter.util.RedisServiceImpl;
import lombok.RequiredArgsConstructor;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PlaceService {
    private final CityMapper cityMapper;
    private final RedisServiceImpl redisService;
    private final StringRedisTemplate redisTemplate;
    public List<City> placeAll(String cityName){
        redisTemplate.opsForValue().setIfAbsent("allCity","");
        String allCity = redisService.get("allCity");
        if (!allCity.trim().equals("")){
            List<City> cities = JSONArray.parseArray(allCity, City.class);
            return cities;
        }
        Map<Integer, City> map = new HashMap<>();
//        存放所有地名
        List<City> list = cityMapper.selectAllByName(cityName);
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
//        将地名放入map
        list.forEach(n->{
            map.put(n.getId(),n);
        });
//        存放顶级地名
        List<City> topPlace = new ArrayList<>();
//        非顶级地名
        List<City> notTopPlace = new ArrayList<>();
//        list存放顶级
        list.forEach(n->{
//            将没有父级的放入top级list
            if (n.getPid()==null){
                topPlace.add(n);
            }else {
//                否则将其放入其父级的子集合
                City parent = map.get(n.getPid());
                if (parent!=null){
                    List<City> children = parent.getChildren();
                    if (children==null){
                        children = new ArrayList<>();
                    }
                    children.add(n);
                    parent.setChildren(children);
                    notTopPlace.add(parent);
                }else {
                    notTopPlace.add(n);
                }
            }
        });
        if (CollectionUtils.isEmpty(topPlace)){
            return notTopPlace;
        }
        return topPlace;
    }
}
